const app = getApp()
const request = require('../../utils/https.js')
let userId = null;
let height, fromUser;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        indicatorDots: true,
        vertical: false,
        dataLoading: false,
        autoplay: true,
        interval: 3000,
        duration: 1000,
        color: 'rgba(255, 255, 255,0.5)',
        active_color: 'rgba(255, 255, 255,1)',
        circular: true,
        active: 0,
        spinShow: true,
        switch: false,
        fixed_status: false,
        toastModalStatus: true,
        has: false,
        fixed: '',
        toZSZQ:false,
        slideWidth: '', //滑块宽
        slideLeft: 0, //滑块位置
        totalLength: '', //当前滚动列表总长
        moveText: "",
        objWidth: 0,
        strWidth: 0,
        moveInfo:false,
        needTip:false,
        fontColor:"#7F7F7F",
        plData:{},
        tabIndex:0,
        sysRatio:0,
        tabMoveWidth:0,
        tabToView:"default",
        bannerEnd:false,
        homeEnd: false,
        activityEnd:false,
        fastEnd:false,
    },

    // 监听滚动条滚动位置
    onPageScroll: function (e) { // 获取滚动条当前位置
        console.log(height)
        const that = this;
        if (e.scrollTop >= height) {
            that.setData({
                fixed_status: true,
                prod_top_fixed_status:true
            })
        } else {
            that.setData({
                fixed_status: false,
                prod_top_fixed_status:false
            })
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        userId = wx.getStorageSync('userId');
        const that = this;

        //获取设备信息
        let systemInfo = wx.getSystemInfoSync();
        that.setData({
            //list: _list,
            windowHeight: app.globalData.navigate_type == 1 ? systemInfo.windowHeight : systemInfo.windowHeight - 35,
            windowWidth: systemInfo.windowWidth,
            navigate_type: app.globalData.navigate_type
        })
        //计算比例
        //that.getRatio();

        that.showLoading()
        //有邀请人
        if (options) {
            if (options.userId) {
                fromUser = options.userId; //上级userId
                wx.setStorageSync("fromUser", fromUser);
            }
            //邀请人二维码进入
            if (options.scene) {
                fromUser = options.scene; //上级userId
                wx.setStorageSync("fromUser", fromUser);
            }
        } else {
            console.log("暂无用户");
        }

        //检查服务是否暂停
        request._get(getApp().Api_url + 'system', {}, function (res) {
            if (res.data.errMsg == 'OK') {
                let flag = res.data.data.on;
                if (!flag) {
                    wx.reLaunch({
                        url: '/pages/stop1/stop1'
                    })
                    return false;
                } else {
                    that.setData({
                        "toZSZQ": true
                    })
                }
            }
        }, function () {
        })

        //banner
        request._get(getApp().Api_url + 'allBanner', { //banner

        }, function (res) {
            if (res.data.errMsg == 'OK') {
                let bannerList = res.data.data;
                that.setData({
                    bannerList: bannerList
                })
            }
            that.setData({
                bannerEnd: true
            })
          /*  request._get(getApp().Api_url + 'goods/allCategory', { //商品类别接口
                pageNum: 1,
                pageSize: 100,
                userId: userId
            }, function (res) {
                if (res.data.errMsg == 'OK') {
                    let navList = res.data.data;
                    that.setData({
                        navList: navList
                    })

                    //商品列表
                    request._get(getApp().Api_url + 'goods/listByCateId', { //商品列表接口
                        cateId: navList[0].cateId,
                        userId: userId,
                        pageNum: 1,
                        pageSize: 100
                    }, function (res) {
                        if (res.data.errMsg == 'OK') {
                            let goodsList = res.data.data;
                            that.setData({
                                goodsList: goodsList
                            })

                        }
                    }, function () {
                    })
                }
            }, function () {
            })*/
        }, function () {
            that.setData({
                bannerEnd: true
            })
        })



        //精选品牌
        request._get(getApp().Api_url + 'func/home', { //商品列表接口
            userId: userId
        }, function (res) {
            if (res.data.errMsg == 'OK') {
                let brandList = res.data.data;
                // const accountInfo = wx.getAccountInfoSync();
                // console.table(accountInfo.miniProgram.appId) // 小程序 appId
                let navList = [];
                let goodsList = {};
                for (let i = 0; i < brandList.length; i++) {
                    let navItem = {
                        "cateName":brandList[i].brandName,
                        "cateId":brandList[i].brandId,
                    }
                    navList.push(navItem);

                    if(i==0){
                        goodsList = brandList[i].prodList;
                    }
                }
                // that.setData({
                //     brandList: brandList
                // })
                that.setData({
                    navList: navList,
                    goodsList:goodsList
                })


            }
            that.setData({
                homeEnd: true
            })
        }, function () {
            that.setData({
                homeEnd: true
            })
        })


        //活动专区
        request._get(getApp().Api_url + 'goods/activity', {
            userId: userId
        }, function (res) {
            if (res.data.errMsg == 'OK') {
                let activityList = res.data.data;
                that.setData({
                    activityList: activityList
                })

            }
            that.setData({
                activityEnd: true
            })
        }, function () {
            that.setData({
                activityEnd: true
            })
        })


        //直升专区接口
        request._get(getApp().Api_url + 'goods/fast', {
            userId: userId
        }, function (res) {
            if (res.data.errMsg == 'OK') {
                let zoneData = res.data.data;
                that.setData({
                    zoneData: zoneData
                })

            }
            that.setData({
                fastEnd: true
            })
        }, function () {
            that.setData({
                fastEnd: true
            })
        })
        /*===获取center_box节点的height===*/
        const query = wx.createSelectorQuery()
        // query.select('#center_box').boundingClientRect()
        query.select('#prod_nav_title').boundingClientRect();
        query.select('#prod_lost_title').boundingClientRect();
        const interval =  setInterval(function () {
            if(that.data.bannerEnd&&that.data.homeEnd&&that.data.activityEnd&&that.data.fastEnd){
                query.selectViewport().scrollOffset()
                query.exec(function (res) {
                    height = res[0].top;
                    that.setData({
                        mHeight: height+'px'
                    })
                    clearInterval(interval)
                })

            }
            
        }, 200)

    },

    goAgent() {
        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            wx.reLaunch({
                url: '/pages/login/login?path=/pages/list/list'
            })
            userId = null;
            return;
        } else {
            wx.navigateTo({
                url: '/packageB/pages/agent/agent'
            })
        }
    },
    //商品类型
    onClick(event) {
        const that = this;
        let navIndex = event.detail.index;
        let navList = that.data.navList;

        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            // wx.reLaunch({
            //   url: '/pages/login/login?path=/pages/list/list'
            // })
            // return;
            userId = null;
        }
        // let nginxUrl = "goods/listByCateId";
        let nginxUrl = "func/cateAndInfo";

        request._get(getApp().Api_url + nginxUrl, { //商品列表接口
            cateId: navList[navIndex].cateId,
            funcId: navList[navIndex].cateId,
            userId: userId,
            pageNum: 1,
            pageSize: 100
        }, function (res) {
            if (res.data.code == 200) {
                // let goodsList = res.data.data;
                let goodsList = res.data.data[0].prodList;
                that.setData({
                    goodsList: goodsList
                })
            }
        }, function () {
        })

    },
    onTabClick(e){

        const that = this;
        console.log("onTabClick")
        const eData = e.currentTarget.dataset;
        let navList = that.data.navList;
        let tabIndex = eData.tabindex;
        let hash1 = eData.hashed;
        let sysRatio = that.data.sysRatio;
        let mlgb = parseInt(170*tabIndex/sysRatio);
        let cnmlgb = mlgb+"px";
        that.setData({
            tabIndex: tabIndex,
            tabMoveWidth:cnmlgb,
            tabToView:hash1,
            goodsList:[],
            dataLoading: true
        })
            // goodsList:null,
            wx.pageScrollTo({
                scrollTop: height,
                duration: 100
               });

        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            userId = null;
        }
        let nginxUrl = "func/cateAndInfo";
        request._get(getApp().Api_url + nginxUrl, { //商品列表接口
            cateId: navList[tabIndex].cateId,
            funcId: navList[tabIndex].cateId,
            userId: userId,
            pageNum: 1,
            pageSize: 100
        }, function (res) {
            if (res.data.code == 200) {
                // let goodsList = res.data.data;
                let goodData = res.data.data;
                if(goodData!=null){
                    let goodsList =goodData[0].prodList;
                    that.setData({
                        goodsList: goodsList
                    })
                }

            }
            that.setData({
                dataLoading: false
            })
        }, function () {
            that.setData({
                goodsList: [],
                dataLoading: false
            })
        })
    },

    //查看详情页
    goOrder(e) {
        const that = this;

        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            // wx.reLaunch({
            //   url: '/pages/login/login?path=/pages/list/list'
            // })
            // return;
            userId = null;
        }
        let goodsId = e.currentTarget.dataset.goodsid;
        let goodsType = e.currentTarget.dataset.kinds;
        let fast = e.currentTarget.dataset.fast;

        wx.navigateTo({
            url: '/pages/gift_details/gift_details?goodsId=' + goodsId + '&show=' + 0 + '&userId=' + fromUser + '&fast=' + fast
        })
    },
    //详情页拉起购物车
    goShopping(e) {
        const that = this;
        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            wx.reLaunch({
                url: '/pages/login/login?path=/pages/list/list'
            })
            return;
        }
        let goodsId = e.currentTarget.dataset.goodsid;
        let goodsType = e.currentTarget.dataset.kinds;
        let fast = e.currentTarget.dataset.fast;

        /*     let userId = wx.getStorageSync("userId");
            if (userId == '' || userId == null || userId == 'undefined') {
              wx.navigateTo({
                url: '/pages/login/login',
              })
              return;
            } */

        wx.navigateTo({
            url: '/pages/gift_details/gift_details?goodsId=' + goodsId + '&show=' + 1 + '&userId=' + fromUser + '&fast=' + fast
        })
    },

    //
    goWebView(e) {
        const that = this;
        let Kinds = e.currentTarget.dataset.kinds;
        let ImgLinks = e.currentTarget.dataset.imglinks;
        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            // wx.navigateTo({
            //   url: '/pages/login/login?path=/pages/list/list'
            // })
            // return;
            userId = null;
        }
        if (Kinds == 0) { //外部
            wx.navigateTo({
                url: '/pages/webview/webview?url=' + ImgLinks,
            })
        } else if (Kinds == 1) { //内部详情页
            wx.navigateTo({
                url: '/pages/gift_details/gift_details?goodsId=' + ImgLinks + '&show=' + 0
            })
        } else if (Kinds == 2) { //精选品牌
            wx.navigateTo({
                url: '/packageA/pages/VIP/VIP?urlId=' + ImgLinks + '&url=Brand'
            })
        }

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        const that = this;
        request._get(getApp().Api_url + 'rank/toAuth', {
            userId: userId
        }, function (res) {

            if (res.data.code == 200) {
                let PartnerData = res.data.data;
                let agentType = PartnerData.result; //-1无任何审核记录 0成功 1审核失败 2待审核 3审核成功
                let reason = PartnerData.reason; //失败原因
                that.setData({
                    PartnerData: PartnerData,
                    agentType: agentType
                })

            }
        }, function () {
        });
        that.goodsNum();
        that.upWish();

    },

    goodsNum() {
        const that = this;
        //购物车数量
        request._get(getApp().Api_url + 'cart/goodsNum', {
            userId: userId
        }, function (res) {
            if (res.data.errMsg == 'OK') {
                if (res.data.data > 0) {
                    //购物车数量接口
                    wx.setTabBarBadge({
                        index: 3,
                        text: res.data.data.toString()
                    })
                } else {
                    wx.removeTabBarBadge({
                        index: 3
                    })
                }
            }
        }, function () {
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    // 下拉刷新回调接口
    onPullDownRefresh: function () {
        const that = this;
        /* this.setData({ //初始化page
          page: 1
        }); */
        wx.stopPullDownRefresh();
        that.onLoad();
        that.setData({
            active: 0
        })

    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
    },
    //加载loading弹出层
    showLoading: function () {
        let that = this;
        let timer = null;
        that.setData({
            toastModalStatus: true,
        });
        clearInterval(timer);
        timer = setTimeout(function () {
            that.setData({
                toastModalStatus: false,
            });
        }, 1000);
    },
    /**
     * 朋友圈转发
     * **/
    onShareTimeline: function () {
        return {
            title: '快美甄选',
            query: "userId=" + userId,
            imageUrl: ''
        }
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        /* wx.showShareMenu({
          withShareTicket: true,
          menus: ['shareAppMessage', 'shareTimeline']
        }) */
        if (res.from === 'button') {
            // 来自页面内转发按钮
            return {
                title: '快美甄选',
                path: '/pages/list/list?userId=' + userId
            }
        } else {
            return {
                title: '快美甄选',
                path: '/pages/list/list?userId=' + userId
            }
        }
    },
    goVIP(e) {
        let urlId = e.currentTarget.dataset.id;
        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            // wx.reLaunch({
            //   url: '/pages/login/login?path=/pages/list/list'
            // })
            // return;
            userId = null;
        }
        wx.navigateTo({
            url: '/packageA/pages/VIP/VIP?urlId=' + urlId + '&url=VIP'
        })
    },
    //看直播
    goLive() {
        let roomId = [7] // 填写具体的房间号，可通过下面【获取直播房间列表】 API 获取
        let customParams = encodeURIComponent(JSON.stringify({
            path: 'packageC/pages/live/live',
            pid: 1
        })) // 开发者在直播间页面路径上携带自定义参数（如示例中的path和pid参数），后续可以在分享卡片链接和跳转至商详页时获取，详见【获取自定义参数】、【直播间到商详页面携带参数】章节（上限600个字符，超过部分会被截断）
        wx.navigateTo({
            url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${roomId}&custom_params=${customParams}`
        })
    },
    goSVIP(e) {
        let urlId = e.currentTarget.dataset.id;
        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            // wx.reLaunch({
            //     url: '/pages/login/login?path=/pages/list/list'
            // })
            // return;
            userId = null;
        }
        wx.navigateTo({
            url: '/packageA/pages/VIP/VIP?urlId=' + urlId + '&url=SVIP'
        })
    },
    goZszq() {
        if (userId == '' || userId == null || userId == 'undefined') {
            // wx.reLaunch({
            //     url: '/pages/login/login?path=/pages/list/list'
            // })
            // return;
            userId = null;
        }
        wx.navigateTo({
            url: '/packageB/pages/zszq/zszq'
        })
    },
    //品牌列表
    goBrand(e) {
        let urlId = e.currentTarget.dataset.brandid;
        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            // wx.reLaunch({
            //     url: '/pages/login/login?path=/pages/list/list'
            // })
            // return;
            userId = null;
        }
            // url: '/packageA/pages/VIP/VIP?urlId=' + urlId + '&url=Brand'
        wx.navigateTo({
            url: '/packageA/pages/voder/voder?urlId=' + urlId + '&url=Brand'
            // url: '/packageA/pages/VIP/VIP?urlId=' + urlId + '&url=Brand'
        })
    },
    //升级后的效果
    upWish() {
        const that = this;
        request._get(getApp().Api_url + 'rank/upWish', {
            userId: userId
        }, function (res) {
            if (res.data.code == 200) {
                if (res.data.data.has) {
                    that.setData({
                        fixed: 'fixed'
                    })
                } else {
                    that.setData({
                        fixed: ''
                    })
                }
                that.setData({
                    wishImg: res.data.data.wishImg,
                    has: res.data.data.has
                })

            }
        }, function () {
        })
    },
    postOrder() {
        const that = this;
        request._get(getApp().Api_url + 'rank/upRead', {
            userId: userId
        }, function (res) {
            if (res.data.code == 200) {
                that.setData({
                    has: false,
                    fixed: ''
                })
            }
        }, function () {
        })
    },
    goActivity(e) {
        const that = this;
        let islink = e.currentTarget.dataset.islink;
        let link = e.currentTarget.dataset.link;
        let linktype = e.currentTarget.dataset.linktype;
        let titles = e.currentTarget.dataset.titles;
        let userId = wx.getStorageSync("userId");
        if (userId == '' || userId == null || userId == 'undefined') {
            // wx.navigateTo({
            //     url: '/pages/login/login?path=/pages/list/list'
            // })
            // return;
            userId = null;
        }
        if (islink == 0) {
            if (linktype == 2) { //外部
                wx.navigateTo({
                    url: '/pages/webview/webview?url=' + link,
                })
            } else if (linktype == 0) { //内部详情页
                wx.navigateTo({
                    url: '/pages/gift_details/gift_details?goodsId=' + link + '&show=' + 0
                })
            } else if (linktype == 1) { //精选品牌
                wx.navigateTo({
                    url: '/packageA/pages/VIP/VIP?urlId=' + link + '&url=Brand'
                })
            } else if (linktype == 3) { //活动
                let aid = e.currentTarget.dataset.aid;
                console.log("aid",aid);
                wx.navigateTo({
                    url: '/packageA/pages/holiday/holiday?urlId=' + link + '&url=holiday'+'&titles='+titles+"&aid="+aid
                })
            }
        } else {

        }

    },


    //slideLeft动态变化
    getleft(e) {
        //slideLeft动态变化
        const that = this;
        let _slideIndex = e.currentTarget.dataset.index;
        let _prodList = that.data.brandList[_slideIndex].prodList.length
        let _totalLength = _prodList * 150; //分类列表总长度
        let _ratio = 230 / _totalLength * (750 / that.data.windowWidth) //滚动列表长度与滑条长度比例
        that.setData({
            slideIndex: _slideIndex,
            slideLeft: e.detail.scrollLeft * _ratio > 230 - (230 / _prodList) ? 230 - (230 / _prodList) : e.detail.scrollLeft * _ratio
        })
    },
    colorRGB2Hex(color) {
        let rgb = color.split(',');
        let r = parseInt(rgb[0].split('(')[1]);
        let g = parseInt(rgb[1]);
        let b = parseInt(rgb[2].split(')')[0]);

        let hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
        return hex;
    },
    pullNoticeAll(){
        const that = this;
        request._get(getApp().Api_url + 'notice/pull', {
            type:"0"
        }, function (resData) {
            let resp = resData.data;
            if(resp.code==200 && resp.data !=null){
                if(resp.data[0]!=undefined){
                    let res = resp.data[0];
                    if(res.strength=="0"){
                        let fontColor2 = that.colorRGB2Hex(res.fontColor);
                        that.setData({
                            moveText:res.content,
                            fontColor:fontColor2,
                            needTip:true
                        })
                    } else if(res.strength =="1"){
                        let info = wx.getSystemInfoSync();
                        let w = info.screenWidth;
                        let content = res.content;
                        let len = content.length * 15 + 4;
                        len = 0 - len;
                        if(res.fontColor !=null && res.fontColor !=""){
                            if(res.bgImg !=null && res.bgImg !=""){
                                that.setData({
                                    moveInfo:true,
                                    moveText: content,
                                    objWidth: w + "px",
                                    strWidth: len + "px",
                                    bgImg:"background:"+res.bgImg,
                                    fontColor:"color:"+res.fontColor,
                                    moveSelf:true
                                })
                            }else {
                                that.setData({
                                    moveInfo:true,
                                    moveText: content,
                                    objWidth: w + "px",
                                    strWidth: len + "px",

                                    fontColor:"color:"+res.fontColor,
                                    moveSelf:true
                                })
                            }
                        } else {
                            that.setData({
                                moveInfo:true,
                                moveText: content,
                                objWidth: w + "px",
                                strWidth: len + "px",
                                moveSelf:false
                            })
                        }
                    }
                }
            }
        }, function () {
        })
    }














})